﻿using log4net.Core;
using log4net.Layout;
using log4net.Layout.Pattern;
using System.IO;

namespace XieCan.AspMVC.Log4net
{

    public class Log4CustomLayout : PatternLayout
    {
        public Log4CustomLayout()
        {
            AddConverter("UserId", typeof(UserIdPatternConverter));
            AddConverter("RequestIP", typeof(UserIPPatternConverter));
            AddConverter("RequestUrl", typeof(RequestUrlPatternConverter));
            AddConverter("RequestData", typeof(RequestHeaderPatternConverter));
            AddConverter("RequestMethod", typeof(RequestMethodPatternConverter));
            AddConverter("RequestAgent", typeof(UserAgentPatternConverter));
            AddConverter("IsDeleted", typeof(IsDeletedPatternConverter));
        }
    }

    internal sealed class UserIdPatternConverter : PatternLayoutConverter
    {
        override protected void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            if (loggingEvent.MessageObject is Log4Model logMessage)
                writer.Write(logMessage.UserId);
        }
    }

    internal sealed class UserIPPatternConverter : PatternLayoutConverter
    {
        override protected void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            if (loggingEvent.MessageObject is Log4Model logMessage)
                writer.Write(logMessage.RequestIP);
        }
    }

    internal sealed class RequestUrlPatternConverter : PatternLayoutConverter
    {
        override protected void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            if (loggingEvent.MessageObject is Log4Model logMessage)
                writer.Write(logMessage.RequestUrl);
        }
    }

    internal sealed class RequestHeaderPatternConverter : PatternLayoutConverter
    {
        override protected void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            if (loggingEvent.MessageObject is Log4Model logMessage)
                writer.Write(logMessage.RequestData);
        }
    }

    internal sealed class RequestMethodPatternConverter : PatternLayoutConverter
    {
        override protected void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            if (loggingEvent.MessageObject is Log4Model logMessage)
                writer.Write(logMessage.RequestMethod);
        }
    }

    internal sealed class UserAgentPatternConverter : PatternLayoutConverter
    {
        override protected void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            if (loggingEvent.MessageObject is Log4Model logMessage)
                writer.Write(logMessage.RequestAgent);
        }
    }

    internal sealed class IsDeletedPatternConverter : PatternLayoutConverter
    {
        override protected void Convert(TextWriter writer, LoggingEvent loggingEvent)
        {
            if (loggingEvent.MessageObject is Log4Model logMessage)
                writer.Write(logMessage.IsDeleted);
        }
    }
}
